const StockService = require('./services/stockService');

// 检查当前交易时间状态
function checkTradingStatus() {
  const now = new Date();
  const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
  const isTradingTime = StockService.isTradingTime();
  const nextTradingTime = StockService.getNextTradingTime();
  
  console.log('=== 股票交易时间状态检查 ===');
  console.log(`当前本地时间: ${now.toLocaleString()}`);
  console.log(`当前中国时间: ${chinaTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
  console.log(`是否在交易时间内: ${isTradingTime ? '是' : '否'}`);
  
  if (!isTradingTime) {
    console.log(`下一个交易时间: ${nextTradingTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`);
    const waitTime = nextTradingTime.getTime() - Date.now();
    const waitHours = Math.floor(waitTime / (1000 * 60 * 60));
    const waitMinutes = Math.floor((waitTime % (1000 * 60 * 60)) / (1000 * 60));
    console.log(`距离下次交易还有: ${waitHours}小时${waitMinutes}分钟`);
  }
  
  console.log('\n=== 交易时间说明 ===');
  console.log('交易日: 周一至周五');
  console.log('交易时间: 09:29 - 15:00');
  console.log('非交易时间不会自动更新股票数据');
  
  return isTradingTime;
}

// 手动更新股票数据
async function manualUpdate() {
  console.log('\n=== 手动更新股票数据 ===');
  try {
    console.log('开始手动更新股票数据...');
    const startTime = Date.now();
    const stockData = await StockService.updateAllStocks();
    const endTime = Date.now();
    console.log(`手动更新完成！耗时 ${endTime - startTime}ms，获取到 ${stockData.length} 只股票数据`);
    
    if (stockData.length > 0) {
      console.log('\n更新的股票数据:');
      stockData.forEach(stock => {
        console.log(`${stock.name} (${stock.code}): ¥${stock.price} (开盘: ¥${stock.openPrice})`);
      });
    }
  } catch (error) {
    console.error('手动更新失败:', error.message);
  }
}

// 主函数
async function main() {
  const args = process.argv.slice(2);
  
  if (args.includes('--update') || args.includes('-u')) {
    // 强制手动更新
    await manualUpdate();
  } else {
    // 检查交易时间状态
    const isTradingTime = checkTradingStatus();
    
    if (!isTradingTime) {
      console.log('\n💡 提示: 当前不在交易时间内，如需强制更新数据，请运行:');
      console.log('node check-trading-time.js --update');
    }
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main().catch(console.error);
}

module.exports = {
  checkTradingStatus,
  manualUpdate
};